<script setup lang="ts">
import {ref, watch, toRefs} from 'vue'
import {skyMsgWarning, skyMsgBox, skyMsgError} from "@/utils/sky.js";

interface TableColumn {
  DisplayCaption: string
  DisplayFieldName: string
  DisplayWidth: string
}

interface PageParams {
  pageIndex: number
  pageSize: number
  SortFields?: string
  direction?: string
}

interface Props {
  multiple?: boolean
  title?: string
  width?: number | string
  height?: number | string
  visible?: boolean
  confirmText?: string
  cancelText?: string
  destroyOnClose?: boolean
  fullscreen?: boolean
  loading?: boolean
  footerHidden?: boolean
  columns?: Array<any>
  condition?: Record<string, any>
  fetchMethod: (params: any) => Promise<any> // 新增：传入的获取数据方法
  queryParams?: Record<string, any> // 新增：查询参数
}

const emits = defineEmits<{
  (e: 'skyConfirm', value: any): void
  (e: 'skyCancel'): void
}>()

const props = withDefaults(defineProps<Props>(), {
  multiple: false,
  title: '参数',
  width: 810,
  height: 550,
  visible: false,
  confirmText: '确定',
  cancelText: '取消',
  destroyOnClose: false,
  fullscreen: false,
  loading: false,
  footerHidden: false,
  condition: () => ({}),
  queryParams: () => ({})
});

const visible = ref(false)
const {loading} = toRefs(props)
const confirmLoading = ref(loading)
const load = ref(false)
const total = ref(0)
const tableColumns = ref<TableColumn[]>([])
const tableData = ref<any[]>([])
const select = ref<any>()
const search = ref("")
const selectionList = ref<any[]>([])

const pageParams = ref<PageParams>({
  pageIndex: 1,
  pageSize: 10,
  SortFields: '',
  direction: 'asc'
})

// 暴露给父组件的方法
defineExpose({
  skyOpen,
  skyClose,
  skyQuickClose
})

// 打开弹窗
function skyOpen() {
  visible.value = true
}

// 关闭弹窗
function skyClose() {
  skyMsgBox("您确认进行关闭么？")
    .then(() => {
      // resetState()
      visible.value = false;
      skyMsgWarning("已关闭🌻")
    })
    .catch(() => {
      skyMsgWarning("已取消🌻")
    })
}

// 快速关闭（用于提交后）
function skyQuickClose() {
  resetState()
  skyMsgWarning("已提交🌻")
}

// 重置状态
function resetState() {
  visible.value = false
  // total.value = 0
  // tableData.value = []
  // select.value = undefined
  // selectionList.value = []
  // search.value = ""
  // pageParams.value.pageIndex = 1
}

// 确认选择
function skyConfirm() {
  if (props.multiple) {
    if (selectionList.value.length === 0) {
      return skyMsgError("请指定参数🌻")
    }
    emits('skyConfirm', selectionList.value)
  } else {
    if (!select.value) {
      return skyMsgError("请指定参数🌻")
    }
    emits('skyConfirm', select.value)
  }
}

// 取消
function skyCancel() {
  emits('skyCancel')
}

// 获取数据
async function fetchData() {
  if (!props.fetchMethod) return

  try {
    load.value = true
    const params = {
      ...props.queryParams,
    }

    const res = await props.fetchMethod(params);

    tableData.value = res.data?.list || []
    total.value = res.data?.total || 0

    // 如果是第一次加载且设置了表头
    if (props.columns && tableColumns.value.length === 0) {
      tableColumns.value = props.columns
    }
  } catch (error) {
    skyMsgError(`数据查询失败，请刷新重试🌻 【${error}】`)
  } finally {
    load.value = false
  }
}

// 处理分页变化
function handlePaginationChange() {
  fetchData();
}

// 处理搜索过滤
function handleFilter(val: string) {
  if (val) {
    // 如果有搜索值，重置页码并添加搜索条件
    pageParams.value.pageIndex = 1
    fetchData()
  } else {
    // 如果清空搜索，重置数据
    pageParams.value.pageIndex = 1
    fetchData()
  }
}

// 选择
const handleCurrentChange = (val: any) => {
  select.value = val;
};

// 多选
const handleSelectionChange = (val) => {
  selectionList.value = val;
};

// 监听条件变化
watch(() => props.columns, (newVal) => {
  if (newVal && Object.keys(newVal).length > 0) {
    tableColumns.value = props.columns || [];
    fetchData();
  }
}, {immediate: true});

// 监听可见性变化
watch(() => props.visible, (val) => {
  visible.value = val
})

// 监听visible变化通知父组件
// watch(visible, (val) => {
//   if (!val) {
//     emits('skyCancel')
//   }
// })
</script>

<template>
  <el-dialog
    v-model="visible"
    :title="props.title + '来源'"
    :width="props.width"
    :close-on-click-modal="false"
    append-to-body
    draggable
    :destroy-on-close="props.destroyOnClose"
    :before-close="skyClose"
    :fullscreen="props.fullscreen"
    :loading="props.loading"
  >
    <slot name="header"></slot>
    <div class="container" :style="{ height: typeof props.height === 'number' ? `${props.height}px` : props.height }">
      <!-- 搜索栏 -->
      <el-form>
        <el-row>
          <el-col :xs="{ span: 24 }" :sm="{ span: 12 }">
            <el-form-item label="关键字" prop="search">
              <el-input
                style="width: 100%"
                placeholder="请输入关键字"
                v-model="search"
                @input="handleFilter"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 表格区域 -->
      <div style="height: calc(100% - 100px)" class="sky-flex">
        <!--        @current-change="handleCurrentChange"-->
        <!--        @selection-change="handleSelectionChange"-->
        <el-table
          v-loading="load"
          border
          highlight-current-row
          :data="tableData"
          empty-text="暂时没有数据哟🌻"
          @current-change="handleCurrentChange"
          :row-key="(row: any) => row.id || row[tableColumns[0]?.DisplayFieldName]"
        >
          <el-table-column
            v-if="props.multiple"
            type="selection"
            width="55"
            align="center"
          />

          <el-table-column
            v-for="(col) in tableColumns"
            :key="col.DisplayCaption"
            align="center"
            :width="col.DisplayWidth"
            :label="col.DisplayCaption"
            :prop="col.DisplayFieldName"
            :show-overflow-tooltip="true"
          />
        </el-table>
      </div>
      <br/>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pageParams.pageIndex"
        v-model:page-size="pageParams.pageSize"
        v-show="total > 0"
        background
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handlePaginationChange"
        @current-change="handlePaginationChange"
      />
    </div>

    <template #footer v-if="!props.footerHidden">
      <span class="dialog-footer">
        <el-button
          type="primary"
          loading-icon="Eleme"
          :loading="confirmLoading"
          v-throttle="skyConfirm"
        >
          {{ props.confirmText }}
        </el-button>
        <el-button type="danger" @click="skyCancel">
          {{ props.cancelText }}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.container {
  //overflow-x: initial;
  //overflow-y: auto;
}

.el-dialog {
  border-top-left-radius: 8px !important;
  border-top-right-radius: 8px !important;
  padding-top: 0;

  .el-dialog__header {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 50px !important;
    padding: 0 0 6px 0;
    @apply dark:bg-#141414;

    .el-dialog__title {
      font-family: YouYuan;
      font-size: 18px;
      font-weight: 500;
    }
  }

  .el-dialog__body {
    padding: 0;
  }

  .el-dialog__footer {
    padding: 10px;
  }
}

.el-dialog__body {
  padding: 10px;
}

.el-dialog__headerbtn {
  padding-bottom: 10px !important;

  .el-dialog__close {
    border: 1px solid;
    border-radius: 10px;
  }
}
</style>
